#include "sm2.h"
#include <openssl/pem.h>
#include <openssl/err.h>
#include <stdio.h>
#include <string.h>

void handleErrors() {
    ERR_print_errors_fp(stderr);
    abort();
}

void sm2_encrypt_decrypt() {
    SM2_KEY key;
    unsigned char *plaintext = (unsigned char *)"Hello, SM2!";
    unsigned char ciphertext[256];
    unsigned char decrypted[256];
    size_t ciphertext_len, decrypted_len;

    // Generate SM2 key pair
    if (!SM2_keygen(&key)) {
        handleErrors();
    }

    // SM2 Encrypt
    ciphertext_len = SM2_encrypt(key.public_key, plaintext, strlen((char *)plaintext), ciphertext);
    printf("Ciphertext Length: %zu\n", ciphertext_len);

    // SM2 Decrypt
    decrypted_len = SM2_decrypt(key.private_key, ciphertext, ciphertext_len, decrypted);
    decrypted[decrypted_len] = '\0';
    printf("Decrypted: %s\n", decrypted);
}

void sm2_sign_verify() {
    SM2_KEY key;
    unsigned char *message = (unsigned char *)"This is a test message.";
    unsigned char signature[128];
    size_t sig_len;

    // Generate SM2 key pair
    if (!SM2_keygen(&key)) {
        handleErrors();
    }

    // SM2 Sign
    sig_len = SM2_sign(key.private_key, message, strlen((char *)message), signature);
    printf("Signature Length: %zu\n", sig_len);

    // SM2 Verify
    if (SM2_verify(key.public_key, message, strlen((char *)message), signature, sig_len)) {
        printf("Signature is valid.\n");
    } else {
        printf("Signature is invalid.\n");
    }
}

int main() {
    sm2_encrypt_decrypt();
    sm2_sign_verify();
    return 0;
}

